<template>
  <el-dialog
    ref="sele"
    :visible="showDistributeDialog"
    @close="close"
    title="选择分发部门"
    width="500px"
  >
    <el-checkbox v-model="selectAll" @change="selectAllOptions">全选</el-checkbox>
    <el-checkbox v-model="selectLevel1" v-if="uniqueLevel.has(1)" @change="handleLevelChange(1,selectLevel1)">一级部门
    </el-checkbox>
    <el-checkbox v-model="selectLevel2" v-if="uniqueLevel.has(2)" @change="handleLevelChange(2,selectLevel2)">二级部门
    </el-checkbox>
    <el-checkbox v-model="selectLevel3" v-if="uniqueLevel.has(3)" @change="handleLevelChange(3,selectLevel3)">三级部门
    </el-checkbox>
    <el-checkbox-group v-model="selectedOptions">
      <el-checkbox v-for="(level, departmentName) in options" :key="departmentName" :label="departmentName">
        {{departmentName}}
      </el-checkbox>
    </el-checkbox-group>
    <!-- 按钮 -->
    <el-row type="flex" justify="center" style="margin-top: 40px;">
      <el-col :span="12">
        <el-button size="mini" type="primary" @click="checkNumOfSecondments">确定</el-button>
        <el-button size="mini" @click="close">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>

</template>
<script>
  import {getExcelNames, distributeCase, checkNumOfSecondments} from '@/api/employee'

  export default {
    props: {
      showDistributeDialog: {
        type: Boolean,
        default: false
      },
      secondmentId: {
        type: Number,
        default: null
      }
    },
    // watch: {
    //   secondmentId(newVal) {
    //     this.getExcelNames(newVal)
    //   }
    // },
    data() {
      return {
        selectAll: false,
        selectLevel1: false,
        selectLevel2: false,
        selectLevel3: false,
        selectedOptions: [],
        options: {},
        uniqueLevel: {}
      };
    },
    methods: {

      getNames() {
        this.getExcelNames(this.secondmentId)
      },
      selectAllOptions() {
        if (this.selectAll) {
          this.selectedOptions = Object.keys(this.options); // 全选时选择所有选项
          this.selectLevel1 = this.uniqueLevel.has(1) ? true : false;
          this.selectLevel2 = this.uniqueLevel.has(2) ? true : false;
          this.selectLevel3 = this.uniqueLevel.has(3) ? true : false;
        } else {
          this.selectedOptions = []; // 取消全选时清空选择
          this.selectLevel1 = false;
          this.selectLevel2 = false;
          this.selectLevel3 = false;
        }
      },
      close() {
        this.selectAll = false
        this.selectLevel1 = false
        this.selectLevel2 = false
        this.selectLevel3 = false
        this.options = {}
        this.selectedOptions = []
        this.$emit('update:showDistributeDialog', false)
      },
      async getExcelNames(id) {
        this.options = await getExcelNames(id)
        this.uniqueLevel = new Set(Object.values(this.options))
        console.log(this.uniqueLevel)
        console.log(this.options)
      },
      // 点击确定时调用
      async btnOK() {
        console.log(this.selectedOptions)
        let isFormDataEmpty = true; // 假设formData为空
        const formData = new FormData();
        formData.append("secondmentId", this.secondmentId);
        this.selectedOptions.forEach((departmentName) => {
          formData.append("departmentNames", departmentName);
        });
        console.log(this.selectedOptions)
        // 有个分发的操作
        await distributeCase(formData)

        this.options = []
        // 通知父组件更新
        this.$emit('alertDistributeInfo')
        // 提示消息
        this.close()
      }
      ,
      async checkNumOfSecondments() {
        if (this.selectedOptions.length === 0) {
          this.$message({
            message: '请选择需要分发的部门',
            type: 'warning'
          });
        }else{
          const formData = new FormData();
          formData.append("secondmentId", this.secondmentId);
          this.selectedOptions.forEach((departmentName) => {
            formData.append("departmentNames", departmentName);
          });
          const overLimitInfo = await checkNumOfSecondments(formData);
          let messageContent = '此操作将分发至各部门, 是否继续?\n';
          overLimitInfo.forEach(info => {
            messageContent += `${info}\n\n`;
          });
          this.$confirm(messageContent, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.btnOK()
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消分发'
            });
          });

        }




      }
      ,
      handleLevelChange(level, selectLevel) {
        if (selectLevel) {
          const departmentsToAdd = Object.keys(this.options).filter(departmentName => this.options[departmentName] === level);
          this.selectedOptions = this.selectedOptions.concat(departmentsToAdd);
          this.selectedOptions = [...new Set(this.selectedOptions)];
          console.log(this.selectedOptions);
        } else {
          this.selectedOptions = this.selectedOptions.filter(departmentName => {
            return !(this.options[departmentName] && this.options[departmentName] === level);
          });
        }
      },
    },
  };
</script>
